package com.yc.login.dao;

import com.yc.login.bean.LoginProperties;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

@Repository
public class LoginDao {

    @Resource
    private JdbcTemplate jdbc;

    @Resource
    private LoginProperties loginProperties;

    public List<?> login(String username, String password){
        String sql = "select * from %s where %s=? and %s=?";
        sql = String.format(sql,
                loginProperties.getTableName(),
                loginProperties.getUsernameColumn(),
                loginProperties.getPasswordColumn());
        final String userClass = loginProperties.getUserClass();
        Class<?> cls;
        try {
           cls = Class.forName(userClass);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("用户类错误: " + userClass, e);
        }
        return jdbc.query(sql, new BeanPropertyRowMapper<Object>((Class<Object>) cls){}, username, password);
        // return jdbc.queryForList(sql, username, password);
    }

    public void updatePwd(String username, String password, String newPassword){
        String sql = "update %s set %s=? where %s=? and %s=?";
        sql = String.format(sql,
                loginProperties.getTableName(),
                loginProperties.getPasswordColumn(),
                loginProperties.getUsernameColumn(),
                loginProperties.getPasswordColumn());
        jdbc.update(sql, newPassword, username, password);
    }

    public void updatePwd(String username, String newPassword){
        String sql = "update %s set %s=? where %s=?";
        sql = String.format(sql,
                loginProperties.getTableName(),
                loginProperties.getPasswordColumn(),
                loginProperties.getUsernameColumn());
        jdbc.update(sql, newPassword, username);
    }

    public String selectEmailByUserame(String username){
        String sql = "select %s from %s where %s=?";
        sql = String.format(sql,
                loginProperties.getEmailColumn(),
                loginProperties.getTableName(),
                loginProperties.getUsernameColumn());
        final String email = jdbc.queryForObject(sql, String.class, username);
        return email;
    }

}
